<template>
	<view class="order">
		<!-- 左侧时间 -->
		<view class="order-left">
			<view class="left-time" v-for="(item,index) in foodList" :key="index" :class="{'select':item.select}"
				@click="selectWeek(item)">{{item.week}}
				<view class="small">{{item.day}}</view>
			</view>
			<view style="height: 120rpx;"></view>
		</view>
		<!-- 右侧菜单 -->
		<view class="order-right">
			<u-tabs :list="tabsList" lineWidth="30" lineColor="#5FC48D" :activeStyle="{
		            color: '#303133',
		            fontWeight: 'bold',
		            transform: 'scale(1.05)'
		        }" :inactiveStyle="{
		            color: '#606266',
		            transform: 'scale(1)'
		        }" @click="clickTabs" itemStyle="width: 33%;padding: 10rpx 0;height: 60rpx;line-height: 60rpx;"
				:scrollable='false' :current="tabsIndex"></u-tabs>
			<view style="flex: 1;overflow: auto;">
				<view v-for="(item,index) in foodList" :key="index">
					<view class="order-list" v-show="item.select">
						<view class="item flex item-child" v-for="child in item.foodMenus" :key="child.id">
							<image :src="baseUrl+child.foodPic" mode="" class="item-img"></image>
							<view class="item-cont">
								<span class="item-weight">{{child.foodName}}</span>
								<view class="flex">
									<view class="amount">￥{{child.foodPrice}}</view>
									<u-number-box v-model="child.buyNum" :min="0" :max="100" v-if="timeOut(item.day)">
										<view slot="minus">
											<u-icon name="minus-circle" size="18" v-if="child.buyNum > 0"
												@click="theSum"></u-icon>
										</view>
										<text slot="input" style="width: 80rpx;text-align: center;"
											v-show="child.buyNum > 0">{{child.buyNum}}</text>
										<view slot="plus">
											<u-icon name="plus-circle-fill" color="#5FC48D" size="18"
												@click="theSum"></u-icon>
										</view>
									</u-number-box>
									<view class="" v-else style="font-size: 24rpx;color: #999;">已截止</view>
								</view>
							</view>
						</view>
						<view class="" style="margin-top: 200rpx;" v-if="item.foodMenus.length === 0">
							<u-empty mode="favor" text="暂无菜品"></u-empty>
						</view>
					</view>
				</view>
				<view class="jiezhi-time">
					{{tabsIndex === 0? `早餐截止时间：${breakfastEndTimeDay()} ${breakfastEndTime || ''}`:
					tabsIndex === 1? `午餐截止时间：${lunchEndTime}`:
					`晚餐截止时间：${dinnerEndTime}`}}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		listFoodMenu,
		getSetInfo
	} from '@/api/home.js'
	import dayjs from 'dayjs'
	export default {
		data() {
			return {
				tabsList: [{
					name: '早餐',
					menuType: 0
				}, {
					name: '午餐',
					menuType: 1
				}, {
					name: '晚餐',
					menuType: 2
				}],
				tabsIndex: 0,
				// 正在展示的数据
				foodList: [],
				// 早餐
				zaoFoodList: [],
				// 午餐
				wuFoodList: [],
				// 晚餐
				wanFoodList: [],
				baseUrl: process.uniEnv.VUE_APP_API_ROOT,
				money: 0,
				breakfastEndTime: '',
				lunchEndTime: '',
				dinnerEndTime: '',
				// 为了展示早餐的前一天
				nowChangeDay: ''
			}
		},
		mounted() {
			this.listFoodMenuHttp(0)
			this.listFoodMenuHttp(1)
			this.listFoodMenuHttp(2)
			this.getSetInfoHttp()
		},
		methods: {
			// 判断时间是否超出
			timeOut(time) {
				if (!time) return false
				let _this = this
				if (_this.tabsIndex === 0) {
					// 早餐
					// 先将time转换为日期对象
					const baseDate = new Date(time.replace(/-/g, '/'));
					// 减去一天（24小时 * 60分钟 * 60秒 * 1000毫秒）
					baseDate.setTime(baseDate.getTime() - 24 * 60 * 60 * 1000);
					// 构建前一天的日期字符串（年/月/日）
					const previousDate = `${baseDate.getFullYear()}/${baseDate.getMonth() + 1}/${baseDate.getDate()}`;
					// 比较当前时间是否早于 前一天的 breakfastEndTime
					return new Date() < new Date(`${previousDate} ${_this.breakfastEndTime.replace(/-/g, '/')}`);
				} else if (_this.tabsIndex === 1) {
					// 午餐
					return new Date() < new Date(`${time.replace(/-/g,'/')} ${_this.lunchEndTime.replace(/-/g,'/')}`)
				} else {
					// 晚餐
					return new Date() < new Date(`${time.replace(/-/g,'/')} ${_this.dinnerEndTime.replace(/-/g,'/')}`)
				}
			},
			// 获取截止时间
			getSetInfoHttp() {
				let _this = this;
				getSetInfo().then(res => {
					if (res.success) {
						_this.breakfastEndTime = res.data.breakfastEndTime || ''
						_this.lunchEndTime = res.data.lunchEndTime
						_this.dinnerEndTime = res.data.dinnerEndTime
					}
				})
			},
			// 顶部点击事件
			clickTabs(item) {
				this.tabsIndex = item.index
				this.foodList = item.menuType === 0 ? this.zaoFoodList :
					item.menuType === 1 ? this.wuFoodList :
					this.wanFoodList
			},
			// 暂时早餐截至日期
			breakfastEndTimeDay() {
				if (!this.nowChangeDay) return ''
				const baseDate = new Date(this.nowChangeDay.replace(/-/g, '/'));
				// 减去一天（24小时 * 60分钟 * 60秒 * 1000毫秒）
				baseDate.setTime(baseDate.getTime() - 24 * 60 * 60 * 1000);
				// 构建前一天的日期字符串（年/月/日）
				return `${baseDate.getFullYear()}-${baseDate.getMonth() + 1}-${baseDate.getDate()}`;
			},
			// 切换周几
			selectWeek(item) {
				let _this = this;
				_this.foodList.forEach((e) => {
					e.select = e.day === item.day
				})
				_this.zaoFoodList.forEach((e) => {
					e.select = e.day === item.day
				})
				_this.wanFoodList.forEach((e) => {
					e.select = e.day === item.day
				})
				_this.wuFoodList.forEach((e) => {
					e.select = e.day === item.day
				})
				_this.nowChangeDay = item.day
			},
			// 菜单
			listFoodMenuHttp(num) {
				let _this = this;
				listFoodMenu({
					menuType: num
				}).then(res => {
					if (res.success) {
						let listData = res.data ?? []
						listData.forEach((item) => {
							// 添加周几
							item.week = _this.getWeek(item.day)
							item.select = false
							// 添加购买数量
							item.foodMenus.forEach((e) => {
								e.buyNum = 0
							})
						})
						if (listData.length > 0) {
							listData[0].select = true
							_this.nowChangeDay = listData[0].day
						}
						if (num === 0) {
							_this.zaoFoodList = listData
							_this.foodList = listData
						} else if (num === 1) {
							_this.wuFoodList = listData
						} else {
							_this.wanFoodList = listData
						}
					} else {
						if (num === 0) {
							_this.zaoFoodList = []
							_this.foodList = []
						} else if (num === 1) {
							_this.wuFoodList = []
						} else {
							_this.wanFoodList = []
						}
					}
				})
			},
			//获取今天是星期几 周几
			getWeek(num) {
				var datas = dayjs(num).day()
				var week = ['日', '一', '二', '三', '四', '五', '六']
				return '周' + week[datas]
			},
			// 计算总数
			theSum() {
				let _this = this
				setTimeout(() => {
					_this.money = 0;
					// 计算数值的总和
					_this.zaoFoodList.forEach((item) => {
						item.foodMenus.forEach((e) => {
							if (e.buyNum > 0) {
								_this.money += e.foodPrice * e.buyNum
							}
						})
					})
					_this.wuFoodList.forEach((item) => {
						item.foodMenus.forEach((e) => {
							if (e.buyNum > 0) {
								_this.money += e.foodPrice * e.buyNum
							}
						})
					})
					_this.wanFoodList.forEach((item) => {
						item.foodMenus.forEach((e) => {
							if (e.buyNum > 0) {
								_this.money += e.foodPrice * e.buyNum
							}
						})
					})
					_this.$emit('money', _this.money)
				}, 100)
			},
			// 跳转结算
			goSettle() {
				let _this = this
				let settleList = []
				_this.zaoFoodList.forEach((item) => {
					let settleChild = []
					item.foodMenus.forEach((e) => {
						if (e.buyNum > 0) {
							settleChild.push(e)
						}
					})
					if (settleChild.length > 0) {
						settleList.push({
							'menuType': 0,
							'day': item.day,
							'list': settleChild
						})
					}
				})
				_this.wuFoodList.forEach((item) => {
					let settleChild = []
					item.foodMenus.forEach((e) => {
						if (e.buyNum > 0) {
							settleChild.push(e)
						}
					})
					if (settleChild.length > 0) {
						settleList.push({
							'menuType': 1,
							'day': item.day,
							'list': settleChild
						})
					}
				})
				_this.wanFoodList.forEach((item) => {
					let settleChild = []
					item.foodMenus.forEach((e) => {
						if (e.buyNum > 0) {
							settleChild.push(e)
						}
					})
					if (settleChild.length > 0) {
						settleList.push({
							'menuType': 2,
							'day': item.day,
							'list': settleChild
						})
					}
				})
				let newList = _this.sortMenus(settleList)
				uni.navigateTo({
					url: `/pages/home/settle?settleList=${encodeURIComponent(JSON.stringify(newList))}`
				})
			},
			sortMenus(menus) {
				menus.sort((a, b) => {
					return dayjs(a.day).isBefore(dayjs(b.day)) ? -1 : 1;
				});
				return menus;
			}
		}
	}
</script>

<style scoped lang="scss">
	.order {
		height: 100%;
		overflow: hidden;
		display: flex;

		.order-left {
			height: 100%;
			width: 180rpx;
			background-color: #f3f3f3;
			overflow: auto;

			.left-time {
				text-align: center;
				font-size: 32rpx;
				// line-height: 90rpx;
				// height: 90rpx;
				padding: 16rpx 0;
				font-weight: bold;
				border-bottom: 1px solid #fff;

				.small {
					font-size: 24rpx;
					color: #888;
					font-weight: initial;
				}
			}

			.select {
				color: #fff;
				background-color: #5FC48D;

				.small {
					color: #fff;
				}
			}
		}

		.order-right {
			height: 100%;
			flex: 1;
			display: flex;
			flex-direction: column;

			.jiezhi-time {
				font-size: 24rpx;
				text-align: center;
				color: #999;
				margin: 10rpx;
				padding-bottom: 120rpx;
			}

			.order-list {

				.flex {
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 28rpx;
				}

				.item {
					background-color: #fff;
					margin: 0 20rpx 20rpx;
					border-radius: 10rpx;
					overflow: hidden;
					padding: 20rpx;
				}

				.item-child {
					margin-bottom: 20rpx;
				}

				.item-img {
					width: 180rpx;
					height: 140rpx;
					margin-right: 20rpx;
				}

				.item-cont {
					flex: 1;
					height: 140rpx;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
				}

				.amount {
					color: #ff0000;
				}

				.item-weight {
					font-weight: bold;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
				}

				.item-color9 {
					color: #999;
				}
			}
		}
	}
</style>